package com.example.weather;

import androidx.appcompat.app.AppCompatActivity;
import androidx.databinding.DataBindingUtil;
import androidx.fragment.app.Fragment;
import androidx.lifecycle.ViewModelProvider;
import androidx.viewpager.widget.ViewPager;

import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.provider.ContactsContract;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.view.ViewParent;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.ScrollView;
import android.widget.Toast;

import com.example.weather.Other.NetworkStateBroadcast;
import com.example.weather.city_manager.CityManagerActivity;
import com.example.weather.city_manager.CityManagerAdapter;
import com.example.weather.data.City;
import com.example.weather.data.CityDao;
import com.example.weather.data.WeatherDatabase;
import com.example.weather.databinding.ActivityMainBinding;

import java.util.ArrayList;
import java.util.List;

public class MainActivity extends AppCompatActivity implements View.OnClickListener{
    List<Fragment>fragmentList=new ArrayList<>();
    List<String>cityList=new ArrayList<>();//要显示的城市集合
    List<ImageView>imgList=new ArrayList<>();///表示ViewPager页数指示器显示集合
    private CityFragmentPagerAdapter adapter;//自定义适配器
    private SharedPreferences pref;//轻量级的数据存储
    String[]hotCitys = {"北京","太原"};
    private  int bgNum;
    //以下为修改架构组件的内容
    private ActivityMainBinding binding;
    private MainVM mainVM;
    private WeatherDatabase weatherDatabase;
    private CityDao cityDao;
    //广播
    private NetworkStateBroadcast stateBroadcast=null;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        if(!cityList.isEmpty())
            cityList.clear(); //清空原本数据源
        weatherDatabase=WeatherDatabase.getDatabase(this);
        cityDao=weatherDatabase.getCityDao();
        cityList=getData();
        try {
            Intent intent = getIntent();
            String city = intent.getStringExtra("city");
            if (!cityList.contains(city)&&!TextUtils.isEmpty(city)) {
                cityList.add(city);
                City cc=new City(city);
                cityDao.insetCity(cc);
            }
        }catch (Exception e){
            Log.i("animee","error");
        }
        //初始化viewpager页面
        initPager();
        //以下为修改架构组件的内容
        binding= DataBindingUtil.setContentView(this,R.layout.activity_main);
        mainVM = new ViewModelProvider(this, new ViewModelProvider.NewInstanceFactory()).get(MainVM.class);
        mainVM.setCitylist(cityList);//初始化数据
        binding.mainIvAdd.setOnClickListener(this);//添加点击事件
        binding.mainIvMore.setOnClickListener(this);
        adapter=new CityFragmentPagerAdapter(getSupportFragmentManager(),fragmentList);///创建适配器
        binding.mainVp.setAdapter(adapter);
        initPoint();///创建小圆点指示器
        binding.mainVp.setCurrentItem(fragmentList.size()-1);//设置最后一个城市信息
        setPagerListener();
        setBackGround();
        binding.setCityData(mainVM);
        binding.setLifecycleOwner(this);
        registReceiver();
    }
    @Override
    protected void onRestart() {
        super.onRestart();
        cityList.clear(); //清空原本数据源
        cityList=getData();
        fragmentList.clear();
        initPager();
        adapter.notifyDataSetChanged();
        imgList.clear();
        binding.mainLayoutPoint.removeAllViews();   //将布局当中所有元素全部移除
        initPoint();
        binding.mainVp.setCurrentItem(fragmentList.size()-1);
    }
    private List<String>getData(){
        List cityList=new ArrayList<String>();
        List<City>cities=cityDao.findAll();
        if(cities.isEmpty()) {
            for(String tmp_name:hotCitys){
                cityDao.insetCity(new City(tmp_name));
                System.out.println("插入了城市"+tmp_name+"\n");
            }
            cities=cityDao.findAll();
        }
        for (City c : cities) {
            cityList.add(c.getName());
            System.out.println(c);
        }
        return cityList;
    }
    public void registReceiver(){
        stateBroadcast=new NetworkStateBroadcast();
        IntentFilter filter=new IntentFilter();
        filter.addAction("android.net.conn.CONNECTIVITY_CHANGE");
        filter.setPriority(Integer.MAX_VALUE);
        registerReceiver(stateBroadcast,filter);
    }
    private void setBackGround(){
        pref = getSharedPreferences("bg_pref", MODE_PRIVATE);
        bgNum = pref.getInt("bg", 2);
        switch (bgNum) {
            case 0:
                binding.mainOutLayout.setBackgroundResource(R.mipmap.bg);
                break;
            case 1:
                binding.mainOutLayout.setBackgroundResource(R.mipmap.bg2);
                break;
            case 2:
                binding.mainOutLayout.setBackgroundResource(R.mipmap.bg3);
                break;
        }
    }
    private void setPagerListener(){//设置监听
        binding.mainVp.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
            }
            @Override
            public void onPageSelected(int position) {
                for (int i = 0; i < imgList.size(); i++) {
                    imgList.get(i).setImageResource(R.mipmap.a1);
                }
                imgList.get(position).setImageResource(R.mipmap.a2);
            }

            @Override
            public void onPageScrollStateChanged(int state) {

            }
        });
    }
    private void initPoint(){// 创建小圆点 ViewPager页面指示器的函数
        for(int i=0;i<fragmentList.size();i++){
            ImageView pIv = new ImageView(this);
            pIv.setImageResource(R.mipmap.a1);
            pIv.setLayoutParams(new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT));
            LinearLayout.LayoutParams lp = (LinearLayout.LayoutParams) pIv.getLayoutParams();
            lp.setMargins(0,0,20,0);
            imgList.add(pIv);
            binding.mainLayoutPoint.addView(pIv);
        }
        imgList.get(imgList.size()-1).setImageResource(R.mipmap.a2);
    }
    private void initPager(){// 创建Fragment对象，添加到ViewPager数据源当中
        for(int i=0;i<cityList.size();i++){
            CityWeatherFragment cwFrag=new CityWeatherFragment();
            Bundle bundle=new Bundle();
            bundle.putString("city",cityList.get(i));
            cwFrag.setArguments(bundle);
            fragmentList.add(cwFrag);
        }
    }
    @Override
    public void onClick(View view) {
        switch (view.getId()){
            case R.id.main_iv_add:
                Intent intent_add=new Intent(this, CityManagerActivity.class);
                startActivity(intent_add);
                break;
            case R.id.main_iv_more:
                Intent intent_more=new Intent(this, MoreActivity.class);
                startActivity(intent_more);
                break;
        }
    }

}